package transform

import (
	"time"

	"github.com/showwin/speedtest-go/speedtest"
)

const (
	B  = 1
	KB = 1000 * B
	MB = 1000 * KB
)

const (
	Bit  = 1
	KBit = 1000 * Bit
	MBit = 1000 * KBit
)

const (
	Byte2Bit = 8
)

func SpeedTest(url string, duration int) int64 {
	if duration == 0 {
		return 0
	}
	duration = min(duration, 15)
	var s = speedtest.New()
	s.SetCaptureTime(time.Duration(duration) * time.Second)
	server, err := s.CustomServer(url)
	if err != nil {
		return 0
	}
	server.URL = url
	if err = server.UploadTest(); err != nil {
		return 0
	}
	return int64(server.ULSpeed)
}
